<?php
/*
 Template Name: Search Page
 */

/**
 * @abstract: post complete page
 * @author: HoanVX
 * @version $Id: search-page.php 73 2015-01-18 05:20:09Z voxuanhoan@gmail.com $
 */

$purpose  = ChotroiUtils::convertPostNullToBlank("sPurpose");
$city 	  = ChotroiUtils::convertPostNullToBlank("sCity");
$district = ChotroiUtils::convertPostNullToBlank("sDistrict");
$category = ChotroiUtils::convertPostNullToBlank("sCategory");
$content  = ChotroiUtils::convertPostNullToBlank("sContent");


if (isset($_POST['doSearch'])) {
	$_SESSION['doSearch'] = array(
							'sPurpose'	=> $purpose,
							'sCity'		=> $city,
							'sDistrict'	=> $district,
							'sCategory'	=> $category,
							'sContent'	=> $content
	);
}


// End if Submit
add_style('css/page/search-page.css');
add_script("js/page/search-page.js");
get_header();


?>
<!-- header-section-ends -->
<!-- content-section-starts -->
<div class="content">
	<div class="container">
		<div class="col-sm-12 col-md-12" id="sleft">

			<div class="panel panel-info">
				<div class="panel-heading">
					<h3 class="panel-title">Kết quả tìm kiếm</h3>
				</div>
				<?php
				// Pagination fix (wp paging ko hoat dong voi custome query
				$tempQuery = $wp_query;
				$wp_query   = NULL;

				// $wp_query: is global object (instance of WP_QUERY()
				$wp_query = search($purpose, $city, $district, $category, $content);
				?>
				<div class="panel-body">
					<div class="">
						<p class="s-conditions">
							<span>Mục đích: </span> <span class="lb"><?php echo ChotroiUtils::getValueByKey(CtEnum::$purpose, $purpose);?>;&nbsp;</span>
							<span>Thành phố: </span> <span class="lb"><?php echo ChotroiUtils::getValueByKey(CityEnum::$cities, $city);?>;&nbsp;</span>
							<span>Quận / Huyện: </span> <span class="lb"><?php echo ChotroiUtils::getValueByKey(CityEnum::getDistricts($city), $district);?>;&nbsp;</span>
							<span>Chuyên mục: </span> <span class="lb"><?php echo get_cat_name($category);?>&nbsp;</span>
							<span>Nội dung tìm: </span> <span class="lb"><?php echo $content;?>&nbsp;</span>
						</p>
					</div>
					<div class="separate"></div>
					<p><i>Có&nbsp;&nbsp;<strong><?php echo $wp_query->found_posts;?></strong>&nbsp;&nbsp;kết quả được tìm thấy</i></p>
					<table class="table table-hover table-result">
						<tbody>
							<?php
							if ( $wp_query->have_posts() ) : ?>
								<!-- the loop -->
								<?php while ( $wp_query->have_posts() ) : $wp_query->the_post();
								?>
							<tr>
								<td>
									<div class="s-image-box">
										<a href="<?php the_permalink();?>" target="_top">
											<img src="<?php echo getFirstImageAttach($post->ID);?>">
										</a>
									</div>
								</td>
								<td class="s-table-cell-snippet-close">
									<div class="s-title ">
										<a class="s-title" href="<?php the_permalink();?>"><?php makeSpecialSearchWord(the_title('','',false), $content);?></a>
									</div>
									<div><b>Pages</b> <?php the_content();?></div>
									<div>
										<div class="visibleUrl" dir="ltr" style="word-break: break-all;">
											<?php the_permalink();?>
										</div>
									</div>
								</td>
							</tr>
								<?php endwhile;?>
								<!-- end of the loop -->

								<?php wp_reset_postdata();
								else:
									echo "<tr><td class='no-result'>Nội dung bạn tìm kiếm không có. Vui lòng thử lại với từ khóa khác. </td></tr>";

								endif;

							?>
						</tbody>
					</table>

					<!-- pagination here -->
					<?php

						if (function_exists("pagination")) {
					    	pagination();
						}

						$wp_query = NULL;
						$wp_query = $tempQuery;
					?>

				</div>
			</div>
		</div>
	</div>

	<form action="" method="POST" id="frmPaging">
		<?php //Xu ly phan trang bang js
		TagUtils::hidden("sPurpose", $purpose);
		TagUtils::hidden("sCity", $city);
		TagUtils::hidden("sDistrict", $district);
		TagUtils::hidden("sCategory", $category);
		TagUtils::hidden("sContent", $content);
		?>
	</form>
	<!-- Contact's information -->
<?php get_footer("contact");?>
<!-- END Contact's information -->
</div>
<!-- content-section-ends -->
<!-- footer-section-starts -->
<?php get_footer();?>
<?php

/**
 * Search post follow args conditions
 * @param unknown $purpose: the purpose of the post
 * @param unknown $city: the city which post is publish
 * @param unknown $district: the district which post is publish
 * @param unknown $cat: the category of posts
 * @param unknown $subject: subject will
 * @return mixed
 */
function search($purpose, $city, $district, $cat, $subject) {

	// use to Hack pagination trong wp. vi wp custom query thi pagintation doesn't work
	global $paged;

	$args = array(
			"post_status"	=> array("publish", "draft"),
			"paged"			=> $paged,
			"post_type"		=> "post",
			"s"				=> $subject, // Search body and title Line 2071 \wp-includes\query.php
			"meta_query"	=> array(
									array(
										'key'     => CT_POST_PURPOSE,
										'value'   => $purpose,
										'compare' => "="
									),
								),
	);

	if (!empty($city)) {
		array_push($args["meta_query"], array(
											'key' => CT_CITY,
											'value' => $city,
											'compare' => '=',

									));
	}

	if (!empty($district)) {
		array_push($args["meta_query"], array(
										'key' => CT_DISTRICT,
										'value' => $district,
										'compare' => '=',
		));
	}

	if (!empty($cat)) {
		$args["cat"] = $cat;
	}

	if (!empty($subject)) {
		$args["post_title"] = $subject;
	}

	return new WP_Query($args);
}

/**
 * Get first image in 5 images which user can upload
 * @param unknown $postId
 * @return image path
 */
function getFirstImageAttach($postId) {
	$args = array(
			'order' 	=> 'ASC',
			'post_type' => 'attachment',
			'numberposts' => -1,
			'post_status' => null,
			'post_parent' => $postId
	);

	$attachments = get_posts( $args );
	$imgURI = "";
	if ( $attachments ) {
		$imgURI = wp_get_attachment_image_src($attachments[0]->ID, array(90,106))[0];
	}

	return ChotroiUtils::getUploadImageURI($imgURI);
}

/**
 * Special to words which is contain in the search result. bold words
 * Ex: search keywords: laptop
 *     returned search result: the laptop verry very cheap.
 *     Expected result: the <b>laptop</b> very very cheap.
 * @param unknown $content
 * @param unknown $searchKey
 */
function makeSpecialSearchWord($content, $searchKey) {
	if (strpos( $content, $searchKey) !== false) {
		echo str_replace($content, $searchKey, "<b>$searchKey</b>");
	} else {
		echo $content ."ccdddd";
	}
}
?>